<template>
  <div>
    <el-button
      size="small"
      type="primary"
      @click="choose"
    >选择</el-button>
    <p>
      <template v-if="!tableConfig.sigleSelect">
        <el-tag
          v-for="(item,index) in allSelectedUserList"
          :key="index"
          size="mini"
          @close="removeUser(index)"
          style="margin-right: 10px"
          closable
        >
          {{item.name}}
        </el-tag>
      </template>
      <template v-else>
        <el-input
          ref="sigleInp"
          @focus="choose"
          :value="selectVal"
          id="adadad"
          clearable
          @clear="removeUser"
        />
      </template>
    </p>
    <el-dialog
      :visible.sync="dialogVisible"
      title="选择用户"
      v-if="dialogVisible"
      width="80%"
      append-to-body
    >
      <!-- 搜索表单等 -->
      <s-from
        :formOption="tableConfig"
        @searchFormData="formParamsSet"
      />
      <!-- 展示table-->
      <s-table
        ref="tableCom"
        @selectionChange="selectionChange"
        @loadData="loadData"
        :data="tableData"
        :config="tableConfig"
      ></s-table>
      <span slot="footer">
        <el-button
          @click="dialogVisible = false"
          size="mini"
        >取 消</el-button>
        <el-button
          @click="chooseConfirm"
          size="mini"
          type="primary"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { get as _get } from 'lodash'
import sTable from './table'
import sFrom from './form'
import { getList } from "./mock.js";
export default {
  components: { sTable, sFrom },

  props: {
    scope: Object,
    tableOption: {
      type: Object,
      default: () => {
        return {
          column: [],//table列的配置,例prop:'name',label:'姓名'
          sigleSelect: true,//单选or多选，默认单选
          uniqueProp: '',//table的唯一值
          callback: () => { },//弹窗里点击确定后的回调
        }
      }
    },
  },

  computed: {
    selectVal() {
      return _get(this.allSelectedUserList, '[0].name', '')
    }
  },
  data() {
    return {
      dialogVisible: false,
      // 最终选中的所有数据
      allSelectedUserList: [],
      // 最终选中的全部唯一字段列表
      allUniquePropList: [],
      // 唯一字段
      uniqueProp: 'id',
      // 每次弹窗中选中的所有数据
      allSelectedList: [],
      formSearchData: {},
      tableData: [],
      tableConfig: {
        sigleSelect: true,//是否单选
        selectable: (row, rowIndex) => {
          if (this.allUniquePropList.indexOf(row[this.uniqueProp]) === -1) {
            if (rowIndex === row.index) {
              return false
            } else {
              return true
            }
          }
        },
        pageConfig: {
          pageSizeList: [10, 20, 30],
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        itemList: [
        ],
      }
    }
  },
  mounted() {
    this.initTableOptions()
    this.setInitVal()
    this.loadData()
  },
  methods: {
    initTableOptions() {
      //根据传来的options展示table列表
      const { tableOption } = this
      if (tableOption && Object.keys(tableOption).length) {
        const { column, sigleSelect, rowKey } = tableOption
        this.tableConfig.itemList = column || []
        this.tableConfig.sigleSelect = sigleSelect
        this.tableConfig.uniqueProp = rowKey || 'id'
      }
    },
    setInitVal() {
      // 初始化table里的选择框，根据id来确定
      if (!this.scope) return
      let ids = this.uniqueProp
      // 后端返回数据 [{id: 1,name: '老王'},{id: 11,name: '例子四'}]
      const initData = this.scope
      this.allSelectedUserList = [{ [ids]: initData[ids], name: initData.name }]
    },
    formParamsSet(params) {
      this.formSearchData = params
      this.loadData()
    },
    // 点击选择按钮
    choose() {
      this.allUniquePropList = []
      this.allSelectedUserList.forEach(
        item => {
          this.allUniquePropList.push(item[this.uniqueProp])
        }
      )
      this.allSelectedList = []
      this.dialogVisible = true
      this.updateSelectedMark()
    },

    // 加载数据
    loadData(newPageConfig) {
      // 条数及页数
      if (newPageConfig && newPageConfig.currentPage) {
        this.tableConfig.pageConfig.currentPage = newPageConfig.currentPage
      }
      if (newPageConfig && newPageConfig.pageSize) {
        this.tableConfig.pageConfig.pageSize = newPageConfig.pageSize
      }
      // apis
      // const loadDataApi = _get(this.tableOption, 'loadDataApi', '')
      const loadDataApi = getList
      if (!loadDataApi) return
      loadDataApi(
        {
          currentPage: this.tableConfig.pageConfig.currentPage,
          pageSize: this.tableConfig.pageConfig.pageSize,
          ...this.formSearchData
        }
      )
        .then(res => {
          let data = res.data
          printLog('data', data)
          this.tableData = data.records;
          this.tableConfig.pageConfig.total = data.total
        })
    },
    // 改变多选列的选中状态时，更新选中列表
    selectionChange(pageSelectedList) {
      // 当页唯一字段组成的列表
      let uniquePropList = []
      this.tableData.forEach(row => {
        uniquePropList.push(row[this.uniqueProp])
      })
      // 从全部选中的数据中，过滤掉当前页的数据，再添加当前页选中的数据
      this.allSelectedList = this.allSelectedList.filter(row =>
        !uniquePropList.includes(row[this.uniqueProp])
      ).concat(pageSelectedList)
    },
    // 更新选中标记--选中数据与当页数据的交集，标记为选中状态
    updateSelectedMark() {
      this.$nextTick(
        () => {
          let pageSelectedList = []
          printLog('allSelectedUserList', this.allSelectedUserList)
          this.allSelectedUserList.forEach(row1 => {
            this.tableData.forEach(row2 => {
              if (row1[this.uniqueProp] === row2[this.uniqueProp]) {
                pageSelectedList.push(row2)
              }
            })
          })
          const { tableCom } = this.$refs
          const { $refs: { singleTable } } = tableCom
          const { sigleSelect } = this.tableConfig
          pageSelectedList.forEach(row => {
            if (sigleSelect) {
              singleTable.setCurrentRow(row);
              return
            }
            singleTable.toggleRowSelection(row);

          })
        }
      )
    },
    // 点击选择弹窗的确定按钮
    chooseConfirm() {
      const { sigleSelect } = this.tableConfig
      this.allSelectedUserList = sigleSelect ? this.allSelectedList : this.allSelectedUserList.concat(this.allSelectedList)
      printLog('', '你点击了确定', '你选择的数据:', this.allSelectedUserList, '原表单传来的scope:', this.scope)
      this.dialogVisible = false
      this.dataSubmit()
    },
    // 移除选择的用户
    removeUser(index) {
      this.allSelectedUserList.splice(index, 1);
      this.dataSubmit()
    },
    // 将选择的数据及scope返回
    dataSubmit() {
      const { callback } = this.tableOption
      callback && callback(this.allSelectedUserList, this.scope)
    }
  }
}
</script>
<style scoped>
</style>